package com.wali.common.ccp.spring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * Spring bean工厂类
 * 
 * @author wali
 * @version [版本号, 2018年03月06日]
 */
@Component
public class CcpSpringBeanFactory implements ApplicationContextAware
{
    private static final Logger logger = LoggerFactory.getLogger(CcpSpringBeanFactory.class);
    
    private static ApplicationContext factory = null;
    
    /**
     * 设置spring应用上下文
     * 
     * @author wali
     * @version [版本号, 2018年03月06日]
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)
        throws BeansException
    {
        if (CcpSpringBeanFactory.factory == null)
        {
            CcpSpringBeanFactory.factory = applicationContext;
        }
    }
    
    /**
     * 获得spring应用上下文
     * 
     * @author wali
     * @version [版本号, 2018年03月06日]
     */
    public static ApplicationContext getFactory()
    {
        return factory;
    }

    /**
     * 通过Class的名称获取实例
     *
     */
    public static <T> T getObjectBean(Class<T> clazz)
    {
        T obj = null;
        try
        {
            obj = factory.getBean(clazz);
        }
        catch (Exception e)
        {
            logger.error("getObjectBean", e);
            
        }
        return obj;
        
    }
    
    /**
     * 通过bean的名称获取实例
     * 
     * @param beanName
     */
    @SuppressWarnings("unchecked")
    public static <T> T getObjectBean(String beanName)
    {
        T obj = null;
        try
        {
            obj = (T)factory.getBean(beanName);
        }
        catch (Exception e)
        {
            logger.error("[beanName:{} is not exist]", beanName);
        }
        return obj;
    }
    
}
